package com.dabai.markdownq.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.FileProvider;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dabai.dbutils.dialog.MdcDialog;
import com.dabai.dbutils.popup.menu.PopupMenuUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.DateUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.NetUtils;
import com.dabai.dbutils.utils.OtherPermissionUtils;
import com.dabai.dbutils.utils.SAFUtils;
import com.dabai.dbutils.utils.ShareUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.SharedPreferencesUtils;
import com.dabai.dbutils.utils.StringUtils;
import com.dabai.dbutils.utils.UriUtils;
import com.dabai.dbutils.utils.ZipUtils;
import com.dabai.dbutils.utils.encryption.AESUtils;
import com.dabai.markdownq.BuildConfig;
import com.dabai.markdownq.R;
import com.dabai.markdownq.adapter.DavFileAdapter;
import com.dabai.markdownq.adapter.FileAdapter;
import com.dabai.markdownq.bean.FileData;
import com.dabai.markdownq.utils.ComparatorByLastModified;
import com.dabai.markdownq.utils.OtherUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.progressindicator.CircularProgressIndicator;
import com.google.android.material.slider.Slider;
import com.google.android.material.textfield.TextInputLayout;
import com.paul623.wdsyncer.SyncConfig;
import com.paul623.wdsyncer.SyncManager;
import com.paul623.wdsyncer.api.OnListFileListener;
import com.paul623.wdsyncer.api.OnSyncResultListener;
import com.paul623.wdsyncer.model.DavData;
import com.tencent.bugly.beta.Beta;

import net.lingala.zip4j.ZipFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;


public class SettingsActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 501) {
                if (data != null) {
                    UriUtils uriUtils = new UriUtils(this, data.getData());
                    File tagFile = new File(OtherUtils.getFontDir(this), "font.ttf");
                    uriUtils.copyFile(tagFile);

                    if (tagFile.exists()) {
                        //如果字体存在
                        try {
                            Typeface.createFromFile(tagFile);
                            DBToast.showText(this, "自定义字体成功!", true);
                        } catch (Exception e) {
                            //如果发生意外,就删除损坏字体
                            DBToast.showText(this, "字体损坏!", false);
                            FileUtils.delete(tagFile);
                        }
                    }


                }
            }
        }

    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        Context context;
        private Preference textSize;

        Handler handler = new Handler();

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

            context = getContext();

            assert context != null;
            SharedPreferencesBasicUse.init(context);



            final Preference checkUpdate = getPreferenceManager().findPreference("checkUpdate");
            assert checkUpdate != null;
            checkUpdate.setSummary(BuildConfig.VERSION_NAME + "(" + BuildConfig.VERSION_CODE + ")");

            Preference workDir = getPreferenceManager().findPreference("workDir");
            assert workDir != null;
            workDir.setSummary(OtherUtils.getMarkdownFilesDir(context).getAbsolutePath());

            textSize = getPreferenceManager().findPreference("textSize");
            assert textSize != null;
            textSize.setSummary((int) SharedPreferencesBasicUse.getFloat("textSize", 18) + "sp");

        }


        @SuppressLint("SetTextI18n")
        @Override
        public boolean onPreferenceTreeClick(Preference preference) {
            switch (preference.getKey()) {
                case "rapidNamingNew":

                    MdcDialog.showInputDialog(context, "自定义规则", SharedPreferencesBasicUse.getString("rapidNamingNew", "新文件ddhhmmss"), "请输入文件命名规则", new MdcDialog.OnInputDialogButtonListener() {
                        @Override
                        public void confirm(AlertDialog dialog, String content) {
                            if (content.isEmpty()){
                                DBToast.showYellowToast(context,"请输入至少一个字符!");
                                return;
                            }

                            if (!OtherUtils.legalRules(content)){
                                DBToast.showText(context,"规则违法!",false);
                                return;
                            }

                            SharedPreferencesBasicUse.setString("rapidNamingNew", content);
                            DBToast.showText(context,"修改文件命名规则成功!",true);
                            dialog.dismiss();
                        }
                        @Override
                        public void cancel() {

                        }
                    }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                     break;
                case "useHelp":
                    DabaiUtils.openLinkWithBrowserActivity(context,"https://support.qq.com/embed/phone/134929/blog-archive");
                     break;
                case "customFont":
                    File tagFile2 = new File(OtherUtils.getFontDir(context), "font.ttf");
                    DBToast.showMethodsFeedbackText(context,tagFile2.exists(),"启用成功!","无字体文件!");
                    break;
                case "Watermark":
                    MdcDialog.showInputDialog(context, "自定义水印", SharedPreferencesBasicUse.getString("watermarkText", "默认水印"), "请输入水印文字", new MdcDialog.OnInputDialogButtonListener() {
                        @Override
                        public void confirm(AlertDialog dialog, String content) {
                            if (content.isEmpty()){
                                DBToast.showYellowToast(context,"请输入至少一个字符!");
                                return;
                            }
                            SharedPreferencesBasicUse.setString("watermarkText", content);
                            DBToast.showText(context,"修改水印文字成功!",true);
                            dialog.dismiss();
                        }
                        @Override
                        public void cancel() {

                        }
                    }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);
                    break;
                case "fontFile":

                    File tagFile = new File(OtherUtils.getFontDir(context), "font.ttf");

                    new MaterialAlertDialogBuilder(context)
                            .setItems(new String[]{"选择文件", "恢复默认"}, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (which == 0) {
                                        SAFUtils.openFile(getActivity(), "*/*", 501);
                                    } else if (which == 1) {
                                        if (tagFile.exists()) {
                                            DBToast.showMethodsFeedbackText(context, FileUtils.delete(tagFile.getParent()), "恢复成功!", "恢复失败!");
                                        } else {
                                            DBToast.showYellowToast(context, "无自定义文件!");
                                        }
                                    }
                                }
                            }).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                    break;
                case "feedback":
                    DabaiUtils.openLinkWithBrowserActivity(context, "https://support.qq.com/embed/phone/134929");
                    break;
                case "appInfo":
                    DabaiUtils.toMyAppInfo(context);
                    break;
                case "passwordLock":
                    boolean passwordLock = preference.getSharedPreferences().getBoolean("passwordLock", false);

                    if (passwordLock && !OtherPermissionUtils.hasScreenLocker(context)) {
                        DBToast.showYellowToast(context, "你没有设置屏幕锁!");
                    }

                    break;
                case "workDir":

                    new MaterialAlertDialogBuilder(context)
                            .setTitle("工作空间操作")
                            .setItems(new String[]{"全部打包并分享", "全部归档", "WebDAV备份", "工作空间概览"}, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    switch (which) {
                                        case 0:
                                            if (OtherUtils.getMarkdownFilesDir(context).list().length <= 0) {
                                                DBToast.showYellowToast(context, "啥也没有~");
                                                return;
                                            }
                                            DBToast.showText(context, "正在打包,请稍等...");
                                            try {
                                                File tagFile = new File(context.getExternalFilesDir("tmp"), "MarkdownFiles.zip");
                                                ZipUtils.ZipFolder(OtherUtils.getMarkdownFilesDir(context).getAbsolutePath(), tagFile.getAbsolutePath());
                                                DBToast.showText(context, "打包成功!", true);

                                                ShareUtils.shareFile(context,
                                                        FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", tagFile),
                                                        "*/*");
                                            } catch (IOException e) {
                                                DBToast.showText(context, "打包失败!", false);
                                            }
                                            break;
                                        case 1:

                                            File fileDir = OtherUtils.getMarkdownFilesDir(context);

                                            if (fileDir.list().length <= 0) {
                                                DBToast.showYellowToast(context, "啥也没有~");
                                                return;
                                            }

                                            new MaterialAlertDialogBuilder(context).setTitle("警告")
                                                    .setMessage("是否要归档"+fileDir.list().length+"个文件?")
                                                    .setPositiveButton("确定", (dialog12, which12) ->  {


                                                        for (File soc : Objects.requireNonNull(fileDir.listFiles())) {

                                                            File tag3 = new File(OtherUtils.getRecoveryDir(context), soc.getName());
                                                            if (tag3.exists()) {
                                                                tag3 = new File(OtherUtils.getRecoveryDir(context), DateUtils.getNowTime("hhmmss") + "_" + soc.getName());
                                                            }
                                                            soc.renameTo(tag3);

                                                        }
                                                        if (Objects.requireNonNull(fileDir.listFiles()).length == 0) {
                                                            DBToast.showText(context, "全部归档成功!", true);
                                                        }

                                                    }).setNeutralButton("取消", null).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                                            break;
                                        case 2:

                                            boolean isLogin = SharedPreferencesBasicUse.getBoolean("isLogin", false);

                                            if (isLogin) {
                                                davControl();
                                            } else {
                                                davLogin();
                                            }

                                            break;
                                        case 3:

                                            DabaiUtils.showDialog(context,"工作空间概览",
                                                    "工作控件总体积:"+FileUtils.getFileSizeString(context.getExternalFilesDir(null))
                                                            +"\n文档数量:"+OtherUtils.getMarkdownFilesDir(context).list().length
                                                            +"\n资源体积:"+FileUtils.formatFileSizeToString(FileUtils.getFileSize(OtherUtils.getResourcesDir(context))+FileUtils.getFileSize(OtherUtils.getFontDir(context))+FileUtils.getFileSize(OtherUtils.getSrcDir(context)))
                                                            +"\n缓存体积:"+FileUtils.formatFileSizeToString(FileUtils.getFileSize(OtherUtils.getTmpDir(context))+FileUtils.getFileSize(OtherUtils.getTmpHtmlDir(context)))
                                                            +"\n\n回收站占用:"+FileUtils.getFileSizeString(OtherUtils.getRecoveryDir(context))
                                            ).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);


                                            break;
                                        default:
                                            break;
                                    }



                                }
                            }).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);


                    break;
                case "checkUpdate":
                    for (int i = 0; i < 5; i++) {
                        Beta.checkUpgrade();
                    }
                    break;
                case "shareApp":
                    ShareUtils.shareFromCoolApk(context, R.string.app_name);
                    break;
                case "delDir":

                    View view = getLayoutInflater().inflate(R.layout.dialog_recovery, null);
                    File dir = OtherUtils.getRecoveryDir(context);

                    new MaterialAlertDialogBuilder(context)
                            .setTitle("回收站("+dir.list().length+")")
                            .setView(view)
                            .setNeutralButton("清空", (dialog, which) -> {
                                if (dir.list().length <= 0) {
                                    DBToast.showYellowToast(context, "啥也没有~");
                                    return;
                                }
                                new MaterialAlertDialogBuilder(context).setTitle("提示").setMessage("是否清空回收站?")
                                        .setPositiveButton("确定", (dialog1, which1) -> {
                                            boolean isOk = FileUtils.delete(dir);
                                            DBToast.showText(context, isOk ? "回收站已清空" : "清空失败", isOk);
                                        }).setNeutralButton("取消", null).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);
                            })
                            .setPositiveButton("关闭", null).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                    RecyclerView recyclerView = view.findViewById(R.id.recoveryRecyclerView);

                    recyclerView.setLayoutManager(new LinearLayoutManager(context));
                    recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));


                    File[] files = dir.listFiles();
                    assert files != null;
                    Arrays.sort(files, new ComparatorByLastModified(false));

                    ArrayList<FileData> fileDataList = new ArrayList<>();

                    for (File file : files) {
                        if (!file.getName().toLowerCase().endsWith(".md")) {
                            continue;
                        }
                        FileData fileData = new FileData();
                        fileData.setPath(file.getAbsolutePath());
                        fileData.setFileName(file.getName());
                        fileDataList.add(fileData);
                    }

                    FileAdapter fileAdapter = new FileAdapter(fileDataList);
                    recyclerView.setAdapter(fileAdapter);

                    View viewEmpty = view.findViewById(R.id.view_empty);
                    if (fileAdapter.getData().size() > 0) {
                        viewEmpty.setVisibility(View.GONE);
                    } else {
                        viewEmpty.setVisibility(View.VISIBLE);
                    }


                    fileAdapter.setOnItemClickListener((adapter, view1, position) -> {
                        File soc = new File(fileAdapter.getData().get(position).getPath());
                        PopupMenuUtils.showPopupMenu(context, view1, R.menu.recovery_item_click, new PopupMenuUtils.OnItemListener() {
                            @Override
                            public void clickItem(MenuItem item) {
                                switch (item.getTitle().toString()) {
                                    case "恢复":
                                        File tag1 = new File(OtherUtils.getMarkdownFilesDir(context), soc.getName());

                                        if (tag1.exists()) {
                                            tag1 = new File(OtherUtils.getMarkdownFilesDir(context), DateUtils.getNowTime("hhmmss") + "_" + soc.getName());
                                        }
                                        boolean isCopy = FileUtils.copyFile(soc, tag1, false);
                                        DBToast.showText(context, isCopy ? "恢复成功!" : "恢复失败!", isCopy);
                                        if (isCopy) {
                                            FileUtils.delete(soc);
                                            FileData fileData = (FileData) adapter.getData().get(position);
                                            fileAdapter.remove(fileData);
                                        }
                                        break;
                                    case "彻底删除":
                                        boolean isDel = FileUtils.delete(soc);
                                        DBToast.showText(context, isDel ? "删除成功!" : "删除失败!", isDel);
                                        if (isDel) {
                                            FileData fileData = (FileData) adapter.getData().get(position);
                                            fileAdapter.remove(fileData);
                                        }
                                        break;
                                    default:

                                        break;
                                }
                            }

                            @Override
                            public void onDismiss(PopupMenu menu) {
                            }
                        });
                    });

                    break;
                case "textSize":

                    View view1 = getLayoutInflater().inflate(R.layout.dialog_text_size, null);

                    AtomicReference<Float> textSizeValue = new AtomicReference<>(SharedPreferencesBasicUse.getFloat("textSize", 18));


                    new MaterialAlertDialogBuilder(context)
                            .setTitle("字体大小调节")
                            .setView(view1)
                            .setNeutralButton("取消", null)
                            .setPositiveButton("确认", (dialog, which) -> {


                                boolean isSet = SharedPreferencesBasicUse.setFloat("textSize", textSizeValue.get());

                                if (isSet) {
                                    textSize.setSummary((int) SharedPreferencesBasicUse.getFloat("textSize", 18) + "sp");
                                }

                            }).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                    Slider slider = view1.findViewById(R.id.demoSlider);
                    TextView textView = view1.findViewById(R.id.demoFont);

                    slider.setValue(textSizeValue.get());
                    textView.setText(textSizeValue.get().intValue() + "号字体演示");
                    textSizeValue.set(textSizeValue.get());

                    slider.addOnChangeListener((slider1, value, fromUser) -> {
                        textSizeValue.set(value);
                        textView.setText((int) value + "号字体演示");
                        textView.setTextSize(value);
                    });

                    break;
                default:
                    break;
            }
            return super.onPreferenceTreeClick(preference);
        }


        SyncManager syncManager;

        /**
         * dav控制
         */
        private void davControl() {

            View dia_view = getLayoutInflater().inflate(R.layout.dialog_webdav, null);
            AlertDialog alertDialog = new MaterialAlertDialogBuilder(context).setTitle("WebDAV控制面板")
                    .setView(dia_view)
                    .show();

            alertDialog.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

            ImageButton bu1 = dia_view.findViewById(R.id.imageButton);
            ImageButton bu2 = dia_view.findViewById(R.id.imageButton2);

            CircularProgressIndicator tip = dia_view.findViewById(R.id.tip);
            TextView tipText = dia_view.findViewById(R.id.tipText);
            RecyclerView recyclerView = dia_view.findViewById(R.id.davRecyclerView);
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
            recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));

            new Thread(() -> {


                SyncConfig config = new SyncConfig(context);
                config.setPassWord(AESUtils.decrypt(SharedPreferencesBasicUse.getString("password", ""), "mq"));
                config.setUserAccount(SharedPreferencesBasicUse.getString("username", ""));
                config.setServerUrl(SharedPreferencesBasicUse.getString("webLink", ""));

                syncManager = new SyncManager(context);

                syncManager.listAllFile("MarkdownQ", new OnListFileListener() {
                    @Override
                    public void listAll(List<DavData> davResourceList) {

                        ArrayList<DavData> arrayList = new ArrayList<>();

                        for (DavData davData : davResourceList) {
                            if (!davData.isDirectory() && davData.getContentType().equals("application/zip")) {
                                if (davData.getPath().contains("MarkdownQ") && davData.getName().toLowerCase().contains("MarkdownQ_Backup_".toLowerCase())) {
                                    arrayList.add(davData);
                                }
                            }
                        }

                        Collections.reverse(arrayList);
                        DavFileAdapter davFileAdapter = new DavFileAdapter(arrayList);
                        davFileAdapter.setOnItemClickListener((adapter, view, position) -> {

                            DavData davData = arrayList.get(position);

                            PopupMenuUtils.showPopupMenu(context, view, R.menu.dav_click, new PopupMenuUtils.OnItemListener() {
                                @Override
                                public void clickItem(MenuItem item) {
                                    switch (item.getTitle().toString()) {
                                        case "拉取":

                                            new MaterialAlertDialogBuilder(context).setTitle("提示")
                                                    .setMessage("是否拉取 " + davData.getName() + " 到本地工作空间,此操作不会修改已有的文件,已有的同名文件会做更名处理!")
                                                    .setPositiveButton("拉取并导入", (dialog, which) -> {

                                                        String fileName = davData.getName();

                                                        File tagFile = new File(context.getExternalFilesDir("Documents"), fileName);
                                                        File tagZipFile = new File(context.getExternalFilesDir("Documents"), "RecoveryFile" + DateUtils.getNowTime(3));


                                                        if (NetUtils.getNetType(context) == 2) {
                                                            DBToast.showYellowToast(context, "正在联网拉取,请注意流量使用情况...");
                                                        } else {
                                                            DBToast.showText(context, "正在联网拉取...");
                                                        }

                                                        syncManager.downloadFile(davData.getName(), "MarkdownQ", new OnSyncResultListener() {
                                                            @Override
                                                            public void onSuccess(String result) {

                                                                try {
                                                                    ZipUtils.UnZipFolder(tagFile.getAbsolutePath(), tagZipFile.getAbsolutePath());
                                                                    OtherUtils.copyDir(tagZipFile.getAbsolutePath(), context.getExternalFilesDir(null).getParent(), false);
                                                                    handler.post(() -> DBToast.showText(context, "导入成功!", true));
                                                                    FileUtils.delete(tagFile);
                                                                    FileUtils.delete(tagZipFile);
                                                                } catch (Exception e) {
                                                                    handler.post(() -> DBToast.showText(context, "导入失败!", false));
                                                                }
                                                            }

                                                            @Override
                                                            public void onError(String errorMsg) {
                                                                handler.post(() -> DBToast.showText(context, "拉取失败!", false));
                                                            }
                                                        });

                                                    }).setNeutralButton("取消", null).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

                                            break;
                                        case "删除":

                                            syncManager.deleteFile("MarkdownQ/" + davData.getName(), new OnSyncResultListener() {
                                                @Override
                                                public void onSuccess(String result) {
                                                    handler.post(() -> {
                                                        DBToast.showText(context, "删除成功!", true);
                                                        alertDialog.dismiss();
                                                        davControl();
                                                    });
                                                }

                                                @Override
                                                public void onError(String errorMsg) {
                                                    handler.post(() -> DBToast.showText(context, "删除失败!", false));
                                                }
                                            });

                                            break;
                                        default:
                                            break;
                                    }
                                }

                                @Override
                                public void onDismiss(PopupMenu menu) {

                                }
                            });


                        });
                        handler.post(() -> {
                            recyclerView.setAdapter(davFileAdapter);
                            tip.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                            if (arrayList.isEmpty()) {
                                tipText.setVisibility(View.VISIBLE);
                                recyclerView.setVisibility(View.GONE);
                            }
                        });
                    }

                    @Override
                    public void onError(String errorMsg) {
                        SharedPreferencesBasicUse.setBoolean("isLogin", false);
                        handler.post(() -> {
                            DBToast.showText(context, "请重新登录!", false);
                            alertDialog.dismiss();
                        });
                    }
                });

            }).start();

            bu1.setOnClickListener(v -> {

                tip.setVisibility(View.VISIBLE);
                alertDialog.setCancelable(false);
                bu1.setEnabled(false);
                bu2.setEnabled(false);

                String fileName = "MarkdownQ_Backup_" + DabaiUtils.getDeviceName(context) + "_" + DateUtils.getNowTime(3) + ".zip";

                FileUtils.delete(context.getExternalFilesDir("tmp"));

                File tagFile = new File(context.getExternalFilesDir("tmp"), fileName);

                if (NetUtils.getNetType(context) == 2) {
                    DBToast.showYellowToast(context, "正在上传,请注意流量使用情况...");
                } else {
                    DBToast.showText(context, "正在上传,请稍等...");
                }

                try {

                    new ZipFile(tagFile).addFolder(context.getExternalFilesDir(null));

                    syncManager.uploadFile(fileName, "MarkdownQ", tagFile, new OnSyncResultListener() {
                        @Override
                        public void onSuccess(String result) {
                            handler.post(() -> {
                                DBToast.showText(context, "备份成功!", true);

                                alertDialog.dismiss();
                                davControl();
                                FileUtils.delete(tagFile);

                            });
                        }

                        @Override
                        public void onError(String errorMsg) {
                            handler.post(() -> {
                                DBToast.showText(context, "备份失败!", false);
                                alertDialog.dismiss();
                                FileUtils.delete(tagFile);

                            });
                        }
                    });
                } catch (IOException e) {
                    DBToast.showText(context, "打包失败!" + e.getMessage(), false);
                    alertDialog.dismiss();
                    FileUtils.delete(tagFile);
                }

            });

            bu2.setOnClickListener(v -> {
                SharedPreferencesBasicUse.setBoolean("isLogin", false);
                handler.post(() -> {
                    DBToast.showText(context, "已经退出登录!", true);
                    alertDialog.dismiss();
                });
            });

        }


        /**
         * dav登录
         */
        private void davLogin() {

            View dia_view = getLayoutInflater().inflate(R.layout.dialog_webdav_login, null);
            AlertDialog alertDialog = new MaterialAlertDialogBuilder(context).setTitle("登录")
                    .setView(dia_view)
                    .setCancelable(false)
                    .setPositiveButton("使用帮助", (dialog, which) -> DabaiUtils.openLink(context, "https://help.jianguoyun.com/?tag=webdav"))
                    .setNeutralButton("返回", null).show();

            alertDialog.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_IOS);

            TextInputLayout til1 = dia_view.findViewById(R.id.til1);
            TextInputLayout til2 = dia_view.findViewById(R.id.til2);
            TextInputLayout til3 = dia_view.findViewById(R.id.til3);
            Button bu = dia_view.findViewById(R.id.button);

            Objects.requireNonNull(til1.getEditText()).setText(SharedPreferencesBasicUse.getString("webLink", "https://dav.jianguoyun.com/dav/"));
            Objects.requireNonNull(til2.getEditText()).setText(SharedPreferencesBasicUse.getString("username", ""));

            bu.setOnClickListener(v -> {
                String webLink = til1.getEditText().getText().toString();
                String username = til2.getEditText().getText().toString();
                String password = Objects.requireNonNull(til3.getEditText()).getText().toString();

                SharedPreferencesBasicUse.setString("webLink", webLink);
                SharedPreferencesBasicUse.setString("username", username);

                if (webLink.isEmpty() || username.isEmpty() || password.isEmpty()) {
                    DBToast.showText(context, "全部为必填项!", false);
                    return;
                }
                if (!StringUtils.startWith(webLink, "http://", "https://")) {
                    DBToast.showText(context, "服务器地址必须由http或https开头!", false);
                    return;
                }

                DBToast.showText(context, "正在登录...");
                new Thread(() -> {

                    SyncConfig config = new SyncConfig(context);
                    config.setPassWord(password);
                    config.setUserAccount(username);
                    config.setServerUrl(SharedPreferencesBasicUse.getString("webLink", ""));

                    syncManager = new SyncManager(context);

                    syncManager.uploadString("配置成功提示.txt", "MarkdownQ", "如你所见，MarkdownQ的WebDav服务已经配置成功！", new OnSyncResultListener() {
                        @Override
                        public void onSuccess(String result) {
                            SharedPreferencesBasicUse.setBoolean("isLogin", true);
                            SharedPreferencesBasicUse.setString("password", AESUtils.encrypt(password, "mq"));

                            handler.post(() -> {
                                DBToast.showText(context, "登陆成功!", true);
                                alertDialog.dismiss();
                                davControl();
                            });
                        }

                        @Override
                        public void onError(String errorMsg) {
                            //失败
                            handler.post(() -> DBToast.showText(context, "登陆失败!", false));
                        }
                    });

                }).start();
            });


        }


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        if (item.getItemId() == android.R.id.home) {// 处理返回逻辑
            finish();
            if (SharedPreferencesUtils.getDefaultSharedPreferences(getApplicationContext()).getBoolean("animatedTransitions", false)) {
                overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (SharedPreferencesUtils.getDefaultSharedPreferences(getApplicationContext()).getBoolean("animatedTransitions", false)) {
            overridePendingTransition(com.dabai.uitools.R.anim.push_ios_in, com.dabai.uitools.R.anim.push_ios_out);
        }
    }
}